package com.test.designpattern.proxy.dynamic.cglib.interceptor;

import com.test.designpattern.proxy.dynamic.cglib.extend.DbTransaction;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 代理目标类要实现的方法、以及方法增强
 */
public class UserInterceptor1 implements MethodInterceptor {
    private DbTransaction dbTransaction;

    public UserInterceptor1(DbTransaction dbTransaction){
        this.dbTransaction = dbTransaction;
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if("save".equals(method.getName())){
            //前置增强
            dbTransaction.beginTransaction();

            //目标方法
            Object res = methodProxy.invokeSuper(o, objects);

            //后置增强
            dbTransaction.endTransaction();

            return res;
        }
        return methodProxy.invokeSuper(o, objects);
    }
}
